package com.wandian.cqcsk.mvvm.ranking.rankingpagefragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.UserInfoBean;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMFragment;
import com.mylib.libcore.tools.CSJADTools;
import com.mylib.libcore.tools.TTAdManagerHolder;
import com.mylib.libcore.utils.GlideUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.widget.CustomCoinToast;
import com.wandian.cqcsk.R;
import com.wandian.cqcsk.adapter.rank.RankingPageRecycleAdapter;
import com.wandian.cqcsk.databinding.FragmentRankingPageBinding;
import com.wandian.setting.bean.RankDataBean;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @date 2019/12/16-13:30
 * @description RankingPageFragment
 **/
public class RankingPageFragment extends BaseMVVMFragment<RankingPageFragmentViewModel> {

    private FragmentRankingPageBinding dataBinding;
    private RankingPageRecycleAdapter adapter;
    private String title;
    private UserInfoBean userInfoBean;
    private String rankRecord="";
    //看视频
    private TTRewardVideoAd mRewardVideoAd;
    private TTAdNative mTTAdNative;
    private boolean videoPrepare = false;
    private  int rankNum =0;
    public static RankingPageFragment newInstance(String title) {
        Bundle args = new Bundle();
        args.putString("title", title);
        RankingPageFragment fragment = new RankingPageFragment();
        fragment.setArguments(args);
        return fragment;

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        dataBinding = FragmentRankingPageBinding.inflate(inflater);
        dataBinding.setLifecycleOwner(this);
        return dataBinding.getRoot();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        if(getArguments().getString("title") != null) title = getArguments().getString("title").trim();
        userInfoBean = AppContext.getInstance().getAppPreferencesHelper().getUserInfoBean();
        dataBinding.setViewModel(mViewModel);
        initRecycler();
        initViewData();
        initClink();
        initCSJAD();
    }

    private void initViewData(){
        switch (title){
            case "活跃榜":
                mViewModel.getOtTop();
                break;
            case "战力榜":
                mViewModel.getFightTop();
                break;
            case "闯关榜":
                mViewModel.getEmigratedTop();
                break;
            case "等级榜":
                mViewModel.getExperienceTop();
                break;
        }
        mViewModel.listData.observe(this,rankDataBeans -> {
            if(!UIUtils.isEmpty(rankDataBeans) && rankDataBeans.size()>0){
                adapter.setNewData(rankDataBeans);
                dataBinding.tvMyName.setText(userInfoBean.getNickName()+"");
                dataBinding.tvId.setText("ID:"+userInfoBean.getId());
                GlideUtil.intoHeadImg(getContext(),userInfoBean.getHeadPic(),dataBinding.ivMyHead);
                for(int i=0;i<rankDataBeans.size();i++){
                    if(rankDataBeans.get(i).getId().equals(userInfoBean.getId()+"")){
                        setTitleRank(title.trim(),dataBinding.tvMyRank,rankDataBeans.get(i).getNum()+"");
                        rankNum = i+1;
                        break;
                    }
                }
                if(rankNum>0){
                    dataBinding.tvRewardBtn.setVisibility(View.VISIBLE);
                    dataBinding.tvRankState.setVisibility(View.VISIBLE);
                    dataBinding.tvRankNum.setText("第"+rankNum+"名");
                    rankRecord =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue("rank_id_"+userInfoBean.getId());
                    if(!UIUtils.isEmpty(title) && !rankRecord.contains(title)){
                        dataBinding.tvRewardBtn.setText("领取奖励");
                        dataBinding.tvRewardBtn.setBackground(getResources().getDrawable(R.drawable.button_red_circle_ball));
                    }else {
                        dataBinding.tvRewardBtn.setText("已领取");
                        dataBinding.tvRewardBtn.setBackground(getResources().getDrawable(R.drawable.button_gary_circle_ball));
                    }
                }else {
                    dataBinding.tvRewardBtn.setVisibility(View.VISIBLE);
                    dataBinding.tvRankState.setVisibility(View.GONE);
                    dataBinding.tvRankNum.setText("未上榜");
                }
            } else {
                adapter.setEmptyView(getLayoutInflater().inflate(com.wandian.message.R.layout.empty_view, null));
            }
        });
    }

    private void initClink(){
        dataBinding.tvRewardBtn.setOnClickListener(v -> {
            if(UIUtils.isFastClick())return;
            if(dataBinding.tvRewardBtn.getText().toString().equals("领取奖励")){
                if(userInfoBean.getIsSign()==1) prepareVideo();
                else ToastUtil.show("您今日还未签到，请签到后领取");
            }
        });
    }

    private void  setTitleRank(String title, TextView tv_rank_title, String num){
        switch (title){
            case "活跃榜":
                tv_rank_title.setText("活跃时长:"+num+"分钟");
                break;
            case "战力榜":
                tv_rank_title.setText("战力指数:"+num+"");
                break;
            case "闯关榜":
                tv_rank_title.setText("闯关数:"+num+"关");
                break;
            case "等级榜":
                tv_rank_title.setText("等级:"+num+"级");
                break;
        }
    }

    private void  initRecycler(){
        adapter = new RankingPageRecycleAdapter(R.layout.item_ranking_style_one,title);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        dataBinding.recycle.setLayoutManager(layoutManager);
        dataBinding.recycle.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                RankDataBean bean = (RankDataBean)adapter.getData().get(position);
                if(!UIUtils.isEmpty(bean)){
                    UserInfoBean userInfoBean = AppContext.getInstance().getAppPreferencesHelper().getUserInfoBean();
                    Bundle bundle = new Bundle();
                    bundle.putString("title","动态");
                    bundle.putString("user_id",bean.getId());
                    bundle.putString("user_name",bean.getNickName());
                    bundle.putString("user_head",bean.getHeadPic());
                    bundle.putString("form_id",userInfoBean.getId()+"");
                    bundle.putString("user_des",bean.getDescription()+"");
                    ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_SETTING_USERHEADINFO).with(bundle).navigation();
                }
            }
        });
    }


    //初始化穿山甲广告
    private void initCSJAD( ){
        try{
            TTAdManagerHolder.init(getContext());
            mTTAdNative = TTAdManagerHolder.getTTAdNative(getContext());
            mTTAdNative.loadRewardVideoAd(CSJADTools.getAdSlot("排行奖励",3,"rank"),
                    new TTAdNative.RewardVideoAdListener() {
                        @Override
                        public void onError(int i, String s) {
                            videoPrepare = false;
                        }

                        @Override
                        public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                            videoPrepare = false;
                            if(UIUtils.isEmpty(ttRewardVideoAd)) return;
                            mRewardVideoAd = ttRewardVideoAd;
                        }
                        @Override
                        public void onRewardVideoCached() {
                            videoPrepare = true;
                        }
                    });

        }catch (Exception e){}
    }

    //准备视频
    private void prepareVideo(){
        if (mRewardVideoAd != null && videoPrepare) {
            mRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                @Override
                public void onAdShow() { }

                @Override
                public void onAdVideoBarClick() { }

                @Override
                public void onAdClose() {
                    double coinNum = (4+rankNum/100.0);
                    mViewModel.getTaskCoin(coinNum+"");
                    AppContext.getInstance().getAppPreferencesHelper().setKeyValue("rank_id_"+userInfoBean.getId(),title+rankRecord);
                    dataBinding.tvRewardBtn.setText("已领取");
                    dataBinding.tvRewardBtn.setBackground(getResources().getDrawable(R.drawable.button_gary_circle_ball));
                }

                @Override
                public void onVideoComplete() {}

                @Override
                public void onVideoError() {}

                @Override
                public void onRewardVerify(boolean b, int i, String s, int i1, String s1) { }

                @Override
                public void onSkippedVideo() { }
            });
            //展示广告，并传入广告展示的场景
            mRewardVideoAd.showRewardVideoAd(getActivity(), TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
        } else{
            ToastUtil.show("视频资源准备中，请稍后再试");
            initCSJAD();
        }
    }
}
